package org.example.statemachine.service.impl;

import org.example.statemachine.entity.Order;
import org.example.statemachine.enums.OrderStatus;
import org.example.statemachine.enums.OrderStatusChangeEvent;
import org.example.statemachine.service.OrderService;
import org.example.statemachine.handler.OrderStateMachineHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.statemachine.mapper.OrderMapper;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderStateMachineHandler stateMachineHandler;

    @Override
    public Order createOrder(Order order) {
        // 设置初始状态为待支付
        order.setStatus(OrderStatus.WAIT_PAYMENT.getKey());
        // 保存订单
        baseMapper.insert(order);
        return order;
    }

    @Override
    public boolean changeOrderStatus(Long orderId, OrderStatusChangeEvent event) {
        // 查询订单
        Order order = baseMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        // 转换状态
        return stateMachineHandler.handleEventWithState(orderId,
                OrderStatus.getByKey(order.getStatus()),
                event);
    }
}